package com.learn.egcar1.controller;


import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.learn.egcar1.base.response.JsonResult;
import com.learn.egcar1.base.utils.CacheUtil;
import com.learn.egcar1.mapper.NoticeMapper;
import com.learn.egcar1.pojo.vo.NoticeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@Api(tags = "公告管理模块")
@RequestMapping("/v1/notice/")
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;

    //自动装配redisTemplate
    /*@Autowired
    private RedisTemplate redisTemplate;*/
    @Autowired
    private CacheUtil cacheUtil;

    @GetMapping("list")
    @ApiOperation("01.获取公告列表")
    @ApiOperationSupport(order = 10)
    public JsonResult getNoticeList(){
        /*
        * 设计redis中的key-value：{“vehicle_index”：‘{"code”:"2000"}...’}
        * 1.确认缓存[redis]中是否存在响应数据 get key;
        * 2.缓存中存在：直接返回；
        * 3.缓存中不存在：
        *       到MySQL查询数据库，
        *       将查询结果写入缓存[redis]中 set key value;
        *       返回；
        * */
        /*ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable index = ops.get("vehicle_index");
        if(index!=null){//缓存中存在
            return JsonResult.ok(index);
        }*/
        Serializable index = cacheUtil.get("vehicle_index");
        if(index!=null){
            return JsonResult.ok(index);
        }

        //缓存中不存在,走MySQL
        List<NoticeVO> noticeList = noticeMapper.getNoticeList();
//        ops.set("vehicle_index",(Serializable) noticeList,30, TimeUnit.SECONDS);
        cacheUtil.setExpire("vehicle_index",(Serializable) noticeList,30);

        return JsonResult.ok(noticeList);
    }
}
